package com.example.demo.controller;

import com.example.demo.model.request.FrontendRequest;
import com.example.demo.model.request.StudentQueryRequest;
import com.example.demo.model.response.ApiResult;
import com.example.demo.model.response.PredictionResponse;
import com.example.demo.model.response.SimilarStudentsResponse;
import com.example.demo.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.nio.charset.StandardCharsets;
import com.example.demo.service.TempService;

@RestController
@RequestMapping("/api/v1") // 使用统一的API版本前缀
public class StudentController {
    // 注入服务层
    private final StudentService studentService;
    private final TempService tempService;
    // 添加日志
    private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
    //构造方法
    public StudentController(StudentService studentService, TempService tempService) {
        this.studentService = studentService;
        this.tempService = tempService;
    }
    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ApiResult<String> healthCheck() {
        logger.info("健康检查接口被调用");
        boolean apiConnected = tempService.testExternalApiConnection();
        if (apiConnected) {
            return ApiResult.success("服务正常，外部API可连接");
        } else {
            return ApiResult.success("服务正常，但外部API连接失败");
        }
    }

    /**
     * 导出相似学生Excel接口（基于外部API数据）
     */
    @PostMapping("/students/export")
    public ResponseEntity<byte[]> exportSimilarStudents(@RequestBody StudentQueryRequest request) {
        logger.info("导出相似学生Excel接口被调用，请求: {}", request);
        try {
            byte[] excelData = studentService.exportSimilarStudents(request);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment",
                    new String("相似学生信息.xlsx".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

            logger.info("导出Excel成功，文件大小: {} bytes", excelData.length);
            return new ResponseEntity<>(excelData, headers, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("导出Excel失败", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/students/temp-predict")
    public PredictionResponse predictTemp(@RequestBody FrontendRequest request) {
        try{
            return tempService.predict(request);
        } catch (Exception e) {
            logger.error("预测失败", e);
            return null;
        }
    }

    @PostMapping("/students/temp-similar")
    public SimilarStudentsResponse getSimilarTemp(@RequestBody FrontendRequest request) {
        try{
            return tempService.getSimilarStudents(request);
        } catch (Exception e) {
            logger.error("获取相似学生失败", e);
            return null;
        }
    }
}